//! # 链路监听器
//!
//! 用于本地监听，等待远端节点与本机建立连接

use crate::connection::Connection;
use crate::error::*;
use alloc::boxed::Box;
use async_trait::async_trait;
use core::fmt;
use core::ops::{Deref, DerefMut};

type L = Box<dyn ListenerDriver>;
pub struct Listener(L);
impl Listener {
    pub fn new(l: L) -> Listener {
        Listener(l)
    }
}
impl Deref for Listener {
    type Target = L;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl DerefMut for Listener {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// 链路驱动接口
#[async_trait]
pub trait ListenerDriver: Send {
    /// 获取类型标识
    fn kind(&self) -> &str;
    /// 获取自定义标识
    fn id(&self) -> &str;

    /// 接收链路(可尝试重新监听)
    async fn accept(&mut self) -> Result<Connection, RecvError>;
}
impl PartialEq for dyn ListenerDriver {
    fn eq(&self, other: &Self) -> bool {
        self.kind() == other.kind() && self.id() == other.id()
    }
}
impl fmt::Display for dyn ListenerDriver {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "listener-{}", self.kind())
    }
}
impl fmt::Debug for dyn ListenerDriver {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "listener-{}({})", self.kind(), self.id())
    }
}
